package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.CardConsumption;
import com.finance.mapper.CardConsumptionMapper;
import com.finance.service.CardConsumptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C05
 */
@Slf4j
@Service
public class CardConsumptionServiceImpl extends ServiceImpl<CardConsumptionMapper, CardConsumption> implements CardConsumptionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate) {
        return processOrders(records, searchDate, forceUpdate, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(CardConsumption::getSearchDate, searchDate)
                .eq(CardConsumption::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C05数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                .eq(CardConsumption::getSearchDate, searchDate)
                .eq(CardConsumption::getCinemaId, cinemaId)
                .remove();
        }

        List<CardConsumption> orderList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                CardConsumption order = new CardConsumption();
                
                // 设置影院ID
                order.setCinemaId(cinemaId);
                //消费时间,消费影院名称,消费影院编码,消费影院所属区域,订单号,卡号,卡类型,卡类型编码,卡政策,卡政策编码
                // 转换日期时间
                String consumptionDate = record.get("消费时间");
                if (consumptionDate != null && !consumptionDate.isEmpty()) {
                    order.setConsumptionTime(LocalDateTime.parse(consumptionDate, 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                // 字符串类型字段全部加非空判断
                if (StringUtils.hasText(record.get("消费影院名称"))) {
                    order.setCinemaName(record.get("消费影院名称"));
                }
                if (StringUtils.hasText(record.get("消费影院编码"))) {
                    order.setCinemaCode(record.get("消费影院编码"));
                }
                if (StringUtils.hasText(record.get("消费影院所属区域"))) {
                    order.setCinemaArea(record.get("消费影院所属区域"));
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    order.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("卡号"))) {
                    order.setCardNo(record.get("卡号"));
                }
                if (StringUtils.hasText(record.get("卡类型"))) {
                    order.setCardType(record.get("卡类型"));
                }
                if (StringUtils.hasText(record.get("卡类型编码"))) {
                    order.setCardTypeCode(record.get("卡类型编码"));
                }
                if (StringUtils.hasText(record.get("卡政策"))) {
                    order.setCardPolicy(record.get("卡政策"));
                }
                if (StringUtils.hasText(record.get("卡政策编码"))) {
                    order.setCardPolicyCode(record.get("卡政策编码"));
                }
                if (StringUtils.hasText(record.get("商品类型"))) {
                    order.setProductType(record.get("商品类型"));
                }
                if (StringUtils.hasText(record.get("商品名称"))) {
                    order.setProductName(record.get("商品名称"));
                }
                // 转换票数
                String ticketCount = record.get("票数");
                if (ticketCount != null && !ticketCount.isEmpty()) {
                    order.setTicketCount(Integer.parseInt(ticketCount));
                }
                if (StringUtils.hasText(record.get("影厅"))) {
                    order.setHallName(record.get("影厅"));
                }
                // 转换放映时间
                String showTime = record.get("放映时间");
                if (showTime != null && !showTime.isEmpty()) {
                    order.setShowTime(LocalDateTime.parse(showTime, 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                // 转换金额字段
                String productPrice = record.get("商品价格");
                if (productPrice != null && !productPrice.isEmpty()) {
                    order.setProductPrice(new BigDecimal(productPrice));
                }
                String consumptionAmount = record.get("卡消费金额");
                if (consumptionAmount != null && !consumptionAmount.isEmpty()) {
                    order.setConsumptionAmount(new BigDecimal(consumptionAmount));
                }
                if (StringUtils.hasText(record.get("消费渠道"))) {
                    order.setConsumptionChannel(record.get("消费渠道"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    order.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    order.setOperatorCode(record.get("操作员工号"));
                }
                if (StringUtils.hasText(record.get("发卡影院名称"))) {
                    order.setIssuingCinemaName(record.get("发卡影院名称"));
                }
                if (StringUtils.hasText(record.get("发卡影院编码"))) {
                    order.setIssuingCinemaCode(record.get("发卡影院编码"));
                }
                if (StringUtils.hasText(record.get("发卡影院所属区域"))) {
                    order.setIssuingCinemaArea(record.get("发卡影院所属区域"));
                }
                if (StringUtils.hasText(record.get("发卡影城所属区域编码"))) {
                    order.setIssuingCinemaAreaCode(record.get("发卡影城所属区域编码"));
                }
                if (StringUtils.hasText(record.get("消费影城所属区域编码"))) {
                    order.setConsumptionCinemaAreaCode(record.get("消费影城所属区域编码"));
                }
                if (StringUtils.hasText(record.get("会员ID"))) {
                    order.setMemberId(record.get("会员ID"));
                }
                
                // 设置searchDate
                order.setSearchDate(searchDate);
                
                // 处理退票手续费金额
                String refundFee = record.get("退票手续费金额");
                if (refundFee != null && !refundFee.isEmpty()) {
                    order.setRefundFee(new BigDecimal(refundFee));
                }

                orderList.add(order);
            } catch (Exception e) {
                log.error("处理卡消费记录失败: {}", record, e);
            }
        }

        try {
            if (!orderList.isEmpty()) {
                return saveBatch(orderList) ? orderList.size() : 0;
            }
            return 0;
        } catch (Exception e) {
            log.error("批量保存卡消费数据失败", e);
            throw e;
        }
    }
} 